// -----------------------------------------------------------------------------
// Copyright (c) 2014-2023 All rights reserved
// *********************************************************************************
// Project Name : Mul by Booth index4 and Wallace
// Author       : DFY
// File Name    : booth_encode.v
// Abstract     : booth_encode partial product
 module booth_encode
 	#(parameter WORDLEN = 16)(
 	input	[WORDLEN-1:0]	x,  		
 	input	[2:0]			src,  // y(i+1) , y(i) , y(i-1)

   	output  [WORDLEN+1:0]	p_ext,// 1bit for 2X and -2X,1bit for inverting -2^n-1 to 2^n-1
   	output  				c
 );
//=================================================================================
// Signal and Parameter declaration
//=================================================================================

///y+1,y,y-1///
wire y_h,y,y_l;
wire sel_negative,sel_double_negative,sel_positive,sel_double_positive;
wire [WORDLEN+1:0] x_ext = {{2{x[WORDLEN-1]}},x[WORDLEN-1:0]}; // extend to WORDlLEN+2, 因为补码的正数范围比负数少，因此负数取反需要多一位，另外+-2X也需要一位
//=================================================================================
// Body
//=================================================================================

assign {y_h,y,y_l} = src;
// generate select signal
assign sel_negative =  y_h & (y & ~y_l | ~y & y_l);
assign sel_positive = ~y_h & (y & ~y_l | ~y & y_l);
assign sel_double_negative =  y_h & ~y & ~y_l;
assign sel_double_positive = ~y_h &  y &  y_l;

// generate partial product

// sel_double_positive 时相当于X会左移一位，低位补0，所以省去
assign p_ext[0] =  (sel_negative&~x[0])|(sel_positive&x[0])|(sel_double_negative); 

genvar i;
generate
	for (i = 1; i < WORDLEN+2; i=i+1) begin
		assign p_ext[i] =  (sel_negative&~x_ext[i]) 
					  |(sel_positive&x_ext[i])  
					  |(sel_double_negative&~x_ext[i-1])
					  |(sel_double_positive&x_ext[i-1]);
	end
endgenerate
assign c = sel_negative|sel_double_negative;//取反后要加1,可当做进位

endmodule 
